package com.controller;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.beans.Admin;
import com.beans.Code;
import com.beans.Company;
import com.beans.Menu;
import com.beans.Site;
import com.beans.User;
import com.service.SysManager;
import com.util.FileUtil;
import com.util.StringUtil;
import com.vo.Page;

public class SysController extends UniversalController {
	private SysManager sysManager;

	public SysManager getSysManager() {
		return sysManager;
	}

	public void setSysManager(SysManager sysManager) {
		this.sysManager = sysManager;
	}

	public ModelAndView getIndex(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		return new ModelAndView("index");
	}

	public ModelAndView getExcuteSQL(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		String sql = request.getParameter("sql");
		String msg = null;
		Map map = new HashMap();
		if (sql != null && !"".equals(sql))
			try {
				sysManager.getMenuDao().excuteSQL(sql);
				msg = "执行成功!";
			} catch (Exception e) {
				e.printStackTrace();
				msg = e.getMessage();
			}
		map.put("o", msg);
		return new ModelAndView("admin/sql", map);
	}

	public ModelAndView getViewBaseInfo(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		return new ModelAndView("baseInfo");
	}

	public ModelAndView getHome(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		Map map = new HashMap();
		User u = (User) request.getSession().getAttribute("user");
		if (u != null) {
			map.put("o", u);
			return new ModelAndView("user/Home", map);
		}
		Company c = (Company) request.getSession().getAttribute("company");
		if (c != null) {
			map.put("o", c);
			return new ModelAndView("company/Home", map);
		}
		return new ModelAndView("login");
	}

	public ModelAndView getListTree(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		String code = request.getParameter("code");
		String type = request.getParameter("type");
		Map map = new HashMap();
		List list = null;
		// list = this.sysManager.getListTree(code, Integer.parseInt(type));
		getMessage(response, getJsonFromJSONArray(list));
		return null;
	}
	public ModelAndView getClearSelect(HttpServletRequest request,
			HttpServletResponse response){
		select.clear();
		return null;
	}
	public ModelAndView getSelect(HttpServletRequest request,
			HttpServletResponse response) {
		String type = request.getParameter("type");
		String index = request.getParameter("index");
		String code = request.getParameter("code");
		Map map = new HashMap();
		map.put("type", type);
		List list = null;
		if (!select.containsKey(type)) {
			Page page = getUniversalManager().findPageByCriteria(1, 1000, map,Code.class);
			if (page == null || page.getDataList() == null)
				return null;
			list = page.getDataList();
			select.put(type, list);
		} else
			list = (List) select.get(type);
		String option = "";
		if (code == null || "".equals(code))
			for (Code c : (List<Code>) list) {
				if (c.getCode().equals(index))
					option += "<option value='" + c.getCode() + "' selected>"
							+ c.getName() + "</option>";
				else
					option += "<option value='" + c.getCode() + "'>"
							+ c.getName() + "</option>";
			}
		else
			for (Code c : (List<Code>) list) {
				if (c.getCode().equals(index))
					option += "<option value='" + c.getCode() + "' selected>["
							+ c.getCode() + "] " + c.getName() + "</option>";
				else
					option += "<option value='" + c.getCode() + "'>["
							+ c.getCode() + "] " + c.getName() + "</option>";
			}
		getMessage(response, option);
		return null;
	}

	// 上传文件
	public ModelAndView getUpload(HttpServletRequest request,
			HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map fileMap = multipartRequest.getFileMap();
		String rootPath = request.getRealPath("/");
		String url = "",msg="",success="true";
		User u = (User) request.getSession().getAttribute("user");
		Company c = (Company) request.getSession().getAttribute("company");
		Admin a=(Admin)request.getSession().getAttribute("admin");
		if(u==null&&c==null&&a==null){
			getMessage(response, "{\"success\":"+false+",\"msg\":\"没有登录权限\",\"url\":\"\"}");
			return null;
		}
		try {
			for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
				String key = (String) it.next();
				MultipartFile file = multipartRequest.getFile(key);
				String path = "upload\\" + FileUtil.filePath();
				String fileName = FileUtil.fileName(file.getOriginalFilename());
				File f = new File(rootPath + path);
				if (!f.exists())
					f.mkdirs();
				f = new File(rootPath + path + fileName);
				file.transferTo(f);
				System.out.println(rootPath + path + fileName);
				url += "||" + path + fileName;
			}
		} catch (Exception e) {
			success="false";
			msg=e.getMessage();
			url="";
			e.printStackTrace();
		}
		if (url.length() > 0)
			url = url.substring(2);
		url = url.replace("\\", "/");
		getMessage(response, "{\"success\":\""+success+"\",\"msg\":\"" + msg + "\",\"url\":\""+url+"\"}");
		return null;
	}

	public ModelAndView getMenuList(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		Map map = new HashMap();
		List list = null;
		list = this.sysManager.getMenuDao().findAll(Menu.class);
		map.put("o", list);
		return new ModelAndView("admin/menuList", map);
	}

	public ModelAndView getMenuEdit(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		Map map = new HashMap();
		String id = request.getParameter("id");
		Menu m = null;
		if ("0".equals(id) || "-1".equals(id))
			m = new Menu();
		else
			m = (Menu) this.sysManager.getMenuDao().findByID(Menu.class,
					(Serializable) id);
		map.put("o", m);
		return new ModelAndView("admin/menuEdit", map);
	}

	public ModelAndView getMenuFrame(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		return new ModelAndView("admin/menuFrame");
	}
	public ModelAndView getSaveMenu(HttpServletRequest request,HttpServletResponse response){
		Menu m=new Menu();
		String msg="";
		try {
			bind(request,m);
			Menu m2=(Menu)getUniversalManager().findByID(Menu.class, m.getCode());
			if(m.getpCode()==null||"".equals(m.getpCode()))m.setpCode("0");
			if(m2==null)
				getUniversalManager().insert(m);
			else
				getUniversalManager().update(m);
			msg="操作成功！";
		} catch (Exception e) {
			e.printStackTrace();
			msg="操作失败！";
		}
		getMessage(response, msg);
		return null;
	}
	public ModelAndView getDeletMenu(HttpServletRequest request,HttpServletResponse response){
		String msg="";
		try {
			String code=request.getParameter("code");
			Menu m=(Menu)getUniversalManager().findByID(Menu.class, code);
			if(m!=null)
				getUniversalManager().delete(m);
			msg="操作成功！";
		} catch (Exception e) {
			e.printStackTrace();
			msg="操作失败！";
		}
		getMessage(response, msg);
		return null;
	}
	public ModelAndView getSiteEdit(HttpServletRequest request,
			HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {
		Map map = new HashMap();
		List list=this.sysManager.getMenuDao().findAll(Site.class);
		Site s=null;
		if(list!=null&&list.size()>0)
			s=(Site)list.get(0);
		map.put("o", s);
		return new ModelAndView("admin/siteEdit", map);
	}
	public ModelAndView getSaveSite(HttpServletRequest request,HttpServletResponse response){
		Site s=new Site();
		try {
			bind(request,s);
			getUniversalManager().update(s);
			getMessage(response, "{\"success\":true,\"err\":\"\"}");
		} catch (Exception e) {
			e.printStackTrace();
			getMessage(response, "{\"success\":false,\"err\":\""+e.getMessage()+"\"}");
		}
		return null;
	}
	public ModelAndView getMenuPath(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String url=request.getParameter("url");
		int t=url.indexOf("&");
		if(url!=null&&t>0)
			url=url.substring(0, t);
		t=url.indexOf("?");
		if(t+1==url.length())
			url=url.substring(0,t-1);
		getMessage(response, sysManager.getMenuDao().getPath(url));
		return null;
	}
}